package com.fesine.crm.util;

import com.fesine.commons.entity.Result;
import com.fesine.commons.enums.ResultEnum;
import com.fesine.commons.util.ResultUtils;
import com.fesine.crm.exception.CrmException;
import com.fesine.crm.service.CrmFileService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

/**
 * @description: 文件工具类
 * @author: Fesine
 * @createTime:2017/11/3
 * @update:修改内容
 * @author: Fesine
 * @updateTime:2017/11/3
 */
public class FileUtils {

    private static final Logger logger = LoggerFactory.getLogger(FileUtils.class);

    public static Result importFile(MultipartFile file, String tempFilePath, boolean deleteFlag,
                                    CrmFileService service) {
        String fileName = file.getOriginalFilename();
        String sf = fileName.substring(fileName.lastIndexOf(".") + 1);
        if (!"xls".equals(sf) && !"xlsx".equals(sf)) {
            return ResultUtils.error(500, "文件错误:文件类型不正确，请上传excel格式文件!");
        }
        File filePath = new File(tempFilePath);
        if (!filePath.exists()) {
            mkRecursiveDir(filePath);
        }
        File f = new File(tempFilePath + fileName);
        try {
            file.transferTo(f);
            service.importFile(f);
        } catch (Exception e) {
            logger.error("导入数据失败", e);
            throw new CrmException(ResultEnum.INTERNAL_SERVER_ERROR.getCode(), e.getMessage());
        } finally {
            if (deleteFlag) {
                f.delete();//删除缓存文件
            }
        }
        return ResultUtils.success();
    }

    /**
     * 递归创建目录
     *
     * @param file
     */
    public static void mkRecursiveDir(File file) {
        if (file.getParentFile().exists()) {
            file.mkdir();
        } else {
            mkRecursiveDir(file.getParentFile());
            file.mkdir();
        }
    }
}
